<template>
    <div>
        <div style="margin: 10px 0">
            <el-form :model="pagequery" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="角色名称" prop="title">
                    <el-input
                            v-model="pagequery.roleName"
                            placeholder="请输入角色名称"
                            clearable
                            style="width: 240px;"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="权限字符" prop="title">
                    <el-input
                            v-model="pagequery.roleKey"
                            placeholder="请输入权限字符"
                            clearable
                            style="width: 240px;"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="操作时间">
                    <el-date-picker
                            v-model="dateRange"
                            style="width: 240px"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="dateFormat"
                            :default-time="['00:00:00', '23:59:59']"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="load">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div style="margin: 10px 0">
            <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
            >新增</el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="handleDelete"
            >
                <el-button  style="margin: 0 5px" size="mini" type="danger" icon="el-icon-delete" plain slot="reference">批量删除</el-button>
            </el-popconfirm>
        </div>

        <el-table :data="tableData" border stripe v-loading="loading"
                  @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="角色编号" width="80"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="roleKey" label="权限字符"></el-table-column>
            <el-table-column prop="description" label="描述" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="280" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            v-if="!scope.row.path"
                            @click="selectMenu(scope.row)"
                            slot="reference"><i class="el-icon-menu"></i>分配菜单
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            v-if="!scope.row.path"
                            @click="handleEdit(scope.row)"
                            slot="reference"><i class="el-icon-edit"></i>编辑
                    </el-button>
                    <el-popconfirm
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="handleDelete(scope.row)"
                    >
                        <el-button style="margin: 0 10px" size="mini"
                                   type="text"
                                   slot="reference"><i class="el-icon-delete"></i>删除
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagequery.pageNum"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="pagequery.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="30%">
            <el-form :model="form" label-width="80px" size="small" :rules="rules" ref="roleForm">
                <el-form-item prop="name" label="名称">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="roleKey" label="唯一标识">
                    <el-input v-model="form.roleKey" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="form.description" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
            <el-tree
                    :props="props"
                    :data="menuData"
                    show-checkbox
                    node-key="id"
                    ref="tree"
                    :default-expanded-keys="expends"
                    :default-checked-keys="checks">
         <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i style="margin: 0 0" :class="data.icon"></i> {{ data.name }}</span>
         </span>
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="menuDialogVis = false">取 消</el-button>
                <el-button size="small" type="primary" @click="saveRoleMenu">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        getRolesPage,
        delRoleById,
        saveRoleAndMenu,
        getMenusByRoleId,
        getRole,
        updateRole,
        addRole
    } from '@/api/system/role'
    import {getMenus,getAllMenusId} from '@/api/system/menu'
    import {logout} from "@/api/login";

    export default {
        name: "Role",
        data() {
            return {
                dateRange:'',
                // 遮罩层
                title:'',
                loading: true,
                tableData: [],
                total: 0,
                pagequery: {  //分页查询条件
                    pageNum: 1,
                    pageSize: 5,
                },
                form: {},
                dialogFormVisible: false,
                menuDialogVis: false,
                menuData: [],
                props: {
                    label: 'name',
                },
                expends: [],
                checks: [],
                roleId: 0,
                roleFlag: '',
                menuids: [],
                ids:[],//删除传递id
                rules: {
                    name: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                    ],
                    roleKey: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                    ],
                }
            }
        },
        methods: {
            load() {
                this.loading = true
                getRolesPage(this.pagequery).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                    this.loading = false
                })
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["roleForm"].validate(valid => {
                    if (valid) {
                        if (this.form.id != undefined) {
                            updateRole(this.form).then(res => {
                                if(res.code===200) {
                                    this.$message.success("修改成功");
                                    this.dialogFormVisible = false;
                                    this.load();
                                }
                            });
                        } else {
                            addRole(this.form).then(res => {
                                if(res.code===200) {
                                    this.$message.success("新增成功");
                                    this.dialogFormVisible = false;
                                    this.load();
                                }
                            });
                        }
                    }
                });
            },
            saveRoleMenu() {
                saveRoleAndMenu(this.roleId,this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())).then(res => {
                    let localRoleId = JSON.parse(localStorage.getItem("user")).role.map(k => k.id);
                    if (res.code === 200) {
                        console.log("22")
                        this.menuDialogVis = false
                        // 操作管理员角色后需要重新登录
                        if (localRoleId.indexOf(this.roleId) >= 0) {
                            this.$message.success("绑定成功，请重新登录")
                            logout()
                        }else{
                            this.$message.success("绑定成功")
                        }

                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const roleIds =  row?.id || this.ids;
                if(roleIds.length<=0){
                    this.$message.warning("请选择删除的角色")
                    return
                }
                delRoleById(roleIds).then(res => {
                    if (res.code===200) {
                        this.$message.success("删除成功")
                        this.load();
                    }
                })
            },
            handleAdd() {
                this.title='添加角色'
                this.dialogFormVisible = true
                this.form = {}
            },
            //修改
            handleEdit(row) {
                const roleId = row.id
                getRole(roleId).then(response => {
                    this.form = response.data
                    this.title = '修改角色'
                });
                this.dialogFormVisible = true
            },
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
            },
            reset() {
                this.dateRange=''
                this.pagequery = {
                    pageNum: 1,
                    pageSize: 5,
                    username: "",
                    email: "",
                    address: "",
                }
                this.load()
            },
            handleSizeChange(pageSize) {
                this.pagequery.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pagequery.pageNum = pageNum
                this.load()
            },
            selectMenu(role) {
                this.expends = []
                this.checks = []
                this.roleId = role.id
                this.roleFlag = role.flag

                // 请求菜单数据
                getMenus().then(res => {
                    this.menuData = res.data
                    // 把后台返回的菜单数据处理成 id数组
                    this.expends = this.menuData.map(v => v.id)
                })

                getMenusByRoleId(this.roleId).then(res => {
                    if(res.code!==200){
                        return
                    }
                    this.checks = res.data
                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.menuids.forEach(id => {
                                // 可能会报错：Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setChecked')
                                //把选中父节点后默认全选的子节点取消选中
                                if(this.checks.indexOf(id)<0)
                                    this.$refs.tree.setChecked(id,false)
                            })
                            //设置延时，因为只有弹框渲染出来，才能通过this.$refs.tree取到组件
                        }, 3)
                        this.menuDialogVis = true
                    })
                })
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.load();
            },
            //获取时间区间方法
            dateFormat(picker) {
                this.pagequery.startTime = picker[0]
                this.pagequery.endTime = picker[1]
            },
        },
        created() {
            getAllMenusId().then(r => {
                this.menuids = r.data
            })
            this.load()
        },

    }
</script>


<style>

</style>
